import random
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .models import *
from django.http import JsonResponse
import json
from django.views.decorators.csrf import csrf_exempt


# Create your views here.
@csrf_exempt
#当你的 Django 应用需要接收来自其他系统的请求时，这些请求可能无法携带有效的 CSRF Token，
# 此时可以使用 @csrf_exempt 装饰器来跳过 CSRF 验证。
def toLogin_view(request):
    return render(request, 'login.html')
def login_view(request):
    u=request.POST.get('user','')
    p=request.POST.get('pwd','')
    # print(u)
    if u and p:
        c=student.objects.filter(std_name=u, std_pwd=p).count()
        # print(c)
        if c >= 1:
            c+=1
            # return HttpResponse(f"登录成功")
            return HttpResponseRedirect('/polls/index/')
        else:
            c+=1
            return HttpResponse("用户名或密码错误<a href='javascript:history.back()'>返回上一页</a>")
    else:
        return HttpResponse("请输入完整的用户名和密码<a href='javascript:history.back()'>返回上一页</a>")
    # if u=="张三" and p=="123456":
    #     return HttpResponse("Login Successful")
    # else:
    #     return HttpResponse("input properly")
def toRegister_view(request):#渲染注册页面
    code = ''.join(random.choices('0123456789ABCDEFGHJKLMNPQRSTUVWSY'
                                          'Zabcdefghijkmnpqrstuvwxzy'
                                          , k=4))
    # 将验证码存储到session中(当前会话接口可使用)，session可以在服务器端存储数据，
    # 可以通过request.session['key']来获取session中的值
    request.session['code'] = code
    return render(request, 'register.html', {'code': code})
    # return render(request, 'register.html')
#点击注册后的逻辑
def register_view(request):
    u = request.POST.get('user', '')
    p = request.POST.get('pwd', '')
    verify_code = request.POST.get('verify_code', '')
    code = request.session.get('code', '')
    #requst.session.get是django的session方法，用于从会话中获取之前存储的内容
    #存储在Django会话（session） 中的值，而不是直接从HTML中获取的，即toRegister_view中获取的
    if u and p and verify_code:
        if code == verify_code:
            # std_id=random.randint(0,10)
            std = student(std_name=u, std_pwd=p)
            std.save()
            return HttpResponse("注册成功！<a href='/polls/'>点击这里登录</a>")
        else:
            return HttpResponse("验证码错误<a href='javascript:history.back()'>返回上一页</a>")
    else:
        return HttpResponse("请输入完整账号和密码<a href='javascript:history.back()'>返回上一页</a>")

def toIndex_view(request):#渲染注册页面
    data = student.objects.first()
    return render(request, 'index.html', {'data': data})
#如果两个视图都映射到同一个 URL，Django 会根据定义的顺序选择第一个匹配的视图，导致另一个视图无法被调用。
def toRename_view(request):
    data = student.objects.first()#渲染注册页面
    return render(request, 'rename.html', {'data': data})
# 只要定位到是第几条数据就可以显示出来
def rename_view(request):#渲染注册页面
    data = student.objects.first()
    u = request.POST.get('user', '')
    p = request.POST.get('pwd', '')
    if u and p:
        std = student(std_name=u, std_pwd=p)
        std.save()
        return HttpResponse("修改成功！ <a href='/polls/index/'>回到主页</a>")

    else:
        return HttpResponse("修改失败 <a href='/polls/index/'>回到主页</a>")
# #渲染注册页面
def toDynasty_view(request):
    stdata = student.objects.first()
    if request.method == 'POST':
        establish_name = request.POST.get('name', '')
        establish_time = request.POST.get('establish_time', '')
        process = request.POST.get('process', '')
        system = request.POST.get('political', '')
        military = request.POST.get('military', '')
        demist_time = request.POST.get('demist_time', '')
        meaning = request.POST.get('meaning', '')
        dynasty.objects.create(
            establish_name=establish_name,
            establish_time=establish_time,
            establish_process=process,
            political_system=system,
            military=military,
            demist_time=demist_time,
            history_meaning=meaning
        )
        return redirect('/polls/dynasty/')#redirect：返回一个 HTTP 302 重定向响应，告诉浏览器跳转到指定的 URL。
        # return render(request, 'dynasty.html',{'stdata': stdata})#但是不会实时刷新
        #返回一个 HTTP 200 响应，内容是渲染后的 HTML 页面。
    else:
        datady = dynasty.objects.all()
        return render(request, 'dynasty.html', {
            'stdata': stdata,  # 学生信息
            'datady': datady  # 王朝信息
        })

#改
def dyupdate_view(request,model_name):
    if request.method == 'POST':
        if model_name == 'dynasty':
            try:
                data = json.loads(request.body)
                id = data.get('id')
                update_data = data.get('data')
                dynasty_obj = dynasty.objects.get(id=id)
                for field, value in update_data.items():
                    setattr(dynasty_obj, field, value)
                    #setattr是Python内置函数，用于设置对象的属性值
                dynasty_obj.save()
                return JsonResponse({'success': True})
            except dynasty.DoesNotExist:
                return JsonResponse({'success': False, 'message': '记录不存在'})
            except Exception as e:
                return JsonResponse({'success': False, 'message': str(e)})
    return JsonResponse({'success': False, 'message': '无效请求'})
#改
def chupdate_view(request,model_name):
    if request.method == 'POST':
        if model_name == 'character':
            try:
                data = json.loads(request.body)
                id = data.get('id')
                update_data = data.get('data')
                character_obj = character.objects.get(id=id)
                for field, value in update_data.items():
                    setattr(character_obj, field, value)
                character_obj.save()
                return JsonResponse({'success': True})
            except dynasty.DoesNotExist:
                return JsonResponse({'success': False, 'message': '记录不存在'})
            except Exception as e:
                return JsonResponse({'success': False, 'message': str(e)})
    return JsonResponse({'success': False, 'message': '无效请求'})

def toCharacter_view(request):#渲染注册页面
    stdata = student.objects.first()
    if request.method == 'POST':
        name = request.POST.get('name', '')
        time = request.POST.get('act_time', '')
        background = request.POST.get('background', '')
        life = request.POST.get('life', '')
        belief = request.POST.get('belief', '')
        achievement = request.POST.get('achievement', '')
        evaluation = request.POST.get('evaluation', '')
        character.objects.create(
            act_name=name,
            act_time=time,
            act_background=background,
            act_life=life,
            act_belief=belief,
            act_achievement=achievement,
            act_evaluation=evaluation,
        )
        return redirect('/polls/character/')  # redirect：返回一个 HTTP 302 重定向响应，告诉浏览器跳转到指定的 URL。
        # return render(request, 'dynasty.html',{'stdata': stdata})#但是不会实时刷新
        # 返回一个 HTTP 200 响应，内容是渲染后的 HTML 页面。
    else:
        chtady = character.objects.all()
        # return render(request, 'character.html', {'chtady': chtady})
        return render(request, 'character.html', {
            'stdata': stdata,  # 学生信息
            'datady': chtady  # 王朝信息
        })

def delete_view(request, id, model_name):
    try:
        if model_name == 'dynasty':
            data = dynasty.objects.get(id=id)
            data.delete()
        else:
            data = character.objects.get(id=id)
            data.delete()
    except dynasty.DoesNotExist:
        pass
    # dynasty.objects.filter(id=id).delete()#删除数据
    if model_name == 'dynasty':
        return redirect("/polls/dynasty/")
    else:
        return redirect("/polls/character/")
def tofind_view(request):
    stdata = student.objects.first()
    name = request.POST.get('name')
    if name:
        data = dynasty.objects.filter(establish_name__icontains=name).count()
        cdata=character.objects.filter(act_name__icontains=name).count()
        if data>0:
            #模糊查询，filter()方法返回一个QuerySet对象，包含所有满足条件的记录，
            # values()方法返回一个QuerySet对象，包含所有满足条件的记录的字段值。
            # icontains是模糊查询，即不区分大小写，即包含name的所有记录
            datas=dynasty.objects.filter(establish_name__icontains=name).values(
                'establish_name','establish_time','establish_process',
                'political_system','military','demist_time','history_meaning')
            if datas:
                return render(request, 'find.html', {
                    'stdata': stdata,  # 学生信息
                    'datady': datas  # 王朝信息
                })
                # return render(request, 'find.html', {'datady': datas})
            else:
                return HttpResponse(f"没有查询到相关信息")
        elif cdata>0:
            cdatas=character.objects.filter(act_name__icontains=name).values(
                'act_name','act_time','act_background','act_life',
                'act_belief','act_achievement','act_evaluation')
            if cdatas:
                return render(request, 'find1.html', {
                    'stdata': stdata,  # 学生信息
                    'datady': cdatas  # 王朝信息
                })
            # return render(request, 'find.html', {'datady': datas})
            else:
                return HttpResponse(f"没有查询到相关信息")
        else:
            return HttpResponse(f"请输入有效内容")
    else:
        return HttpResponse(f"请输入内容")

#图表函数
def toChart_view(request):
    # 统计姓氏（取首字）
    counts = {}
    for obj in character.objects.all():
        surname = obj.act_name[0] if obj.act_name else ''
        counts[surname] = counts.get(surname, 0) + 1

    return render(request, 'chart.html', {
        'labels': list(counts.keys()),
        'data': list(counts.values())
    })